package updown.service.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import updown.dao.LoginDao;
import updown.domain.Account;
import updown.handler.ex.ParkException;
import updown.util.DateUtils;
import updown.util.JwtokenUtil;

import java.util.List;

/**
 * <p>Title: ww.kaixin.downupservice.serviceInfo </p>
 * <p>Description:updown: - 登录service </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/5
 * @Version: 1.0
 */
@Slf4j
@Service
public class LoginService {
    @Autowired
    private LoginDao loginDao;
    /**
     * 登录
     * @param superAccount
     */
    public Account login(Account account) {
        Account superAccountIndata = loginDao.getAccountByNameAndPassword(account);
        if(superAccountIndata == null){
            throw new ParkException("您输入的账户或密码有误");
        }
        superAccountIndata.setLastLoginTime(DateUtils.getCurDateTime());
        loginDao.update(superAccountIndata);
        String token = JwtokenUtil.createToken(superAccountIndata);
        Account retAccount = new Account();
        retAccount.setUsername(account.getUsername());
        retAccount.setToken(token);
        return retAccount;
    }

    /**
     * 拦截器
     * @param token
     * @return
     */
    public Account getAccountByToken(String token) {
        String userName = JwtokenUtil.getUserName(token);
        String password = JwtokenUtil.getPassword(token);
        Account account = new Account();
        account.setUsername(userName);
        account.setPassword(password);
        Account accountByNameAndPassword = loginDao.getAccountByNameAndPassword(account);
        if(accountByNameAndPassword == null){
            throw new ParkException("您输入的账户或密码有误,请重新登录");
        }
        return accountByNameAndPassword;
    }

    /**
     * 账户列表
     * @param account
     * @return
     */
    public List<Account> getAccountList(Account account) {
        return loginDao.getAccountList(null);
    }
}
